// util

function delay(f, ms = 300) {
  window.setTimeout(f, ms)
}

// 登录信息
const loginInfo = {
  PATH: "app/login-user",
  getUser() {
    return JSON.parse(window.localStorage.getItem(this.PATH))
  },

  /* 
  data: {
    userid: 123,
    maxAge: 0,
    createTime: 1550050050123,
    token: "aoeuaohtlel",
  }
  */
  setUser(data) {
    try {
      return window.localStorage.setItem(this.PATH, JSON.stringify(data))
    } catch (e) {
      console.log(e)
    }
  },
  removeUser() {
    return window.localStorage.removeItem(this.PATH)
  },
}

// 转换日期格式
function transformDate(date) {
  if (!date) {
    return ""
  }
  let d = new Date(date.replace(" ", "T"))
  return [
    ("0" + d.getUTCFullYear()).slice(-4), "/",
    ("0" + (d.getUTCMonth() + 1)).slice(-2), "/",
    ("0" + d.getUTCDate()).slice(-2), " ",
    ("0" + d.getUTCHours()).slice(-2), ":",
    ("0" + d.getUTCMinutes()).slice(-2), ":",
    ("0" + d.getUTCSeconds()).slice(-2),
  ].join("")
}

const STATUS_OK = "ok"
const STATUS_ERROR = "error"

const MintUI = require("mint-ui")

let alert_open = false

function Alert(message, title) {
  if (!title) {
    title = "错误"
  }
  alert_open = true
  MintUI.MessageBox.alert(message, title).then((action) => {
    if (action === "confirm") {
      alert_open = false
    }
  })
}

// 扫描插件
let useScanPlugin = true

function registerScanner(onSuccess, onError) {
  if (useScanPlugin && window.plugins) {
    if (!onError) {
      onError = (err) => {
        // util.Toast("错误: " + err)
      }
    }
    let newOnSuccess = (data) => {
      if (!alert_open) {
        onSuccess(data)
      }
    }
    plugins.honeywell.listenForScans(newOnSuccess, onError)
  }
}

module.exports = {
  delay,
  loginInfo,

  useScanPlugin,
  registerScanner,
//转换日期格式
  transformDate,

  STATUS_OK,
  STATUS_ERROR,
//自动消失的弹窗
  Toast: MintUI.Toast,
  //Confirm: MintUI.Confirm,
  //只有确认的提示窗
  Alert,
  // 有确认取消的弹窗
  Confirm: MintUI.MessageBox.confirm,
  //loading弹窗
  Indicator: MintUI.Indicator,
}
